<script setup lang="ts">
import HandsonTable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'
import 'handsontable/styles/handsontable.css'
import 'handsontable/styles/ht-theme-main.css'
// import 'handsontable/styles/ht-theme-horizon.css'
import '@/style/handsontable-theme.css'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import { HyperFormula } from 'hyperformula'

import useTheme from '../useTheme'
import { REPORT_FORM_ID, REPORT_ID, REPORT_WATER_TYPE_TEXT } from '@/enum/modules/report'
import type { LoadDataResponse } from './type'
import { HEADER_CELL_CLASS, READONLY_CELL_CLASS, ROUND_NUMBER as _ROUND_NUMBER } from '../config'
import { loadReportDataOfSummaryCompanyWeight } from '@/api/modules/dataReport'

defineOptions({ name: 'SummaryCompanyWeight' })

const props = defineProps<{
  time: string
}>()

const ROUND_NUMBER = _ROUND_NUMBER + 2

registerLanguageDictionary(zhCN)

// register Handsontable's modules
registerAllModules()

const HEADERS = [
  [
    '单位',
    '取水名称',
    '取水量',
    '其中煤矿用水（吨）',
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    '其中洗煤厂用水（吨）',
    null,
    null,
    null,
    null,
    '生态治理绿化',
    '联营单位',
    '外委单位',
    '退水量',
    '疏干水富余量',
    '平衡情况',
  ],
  [
    null,
    null,
    null,
    '井下生产',
    '洗浴',
    '办公生活',
    '食堂',
    '采暖',
    '道路降尘',
    '矿区内绿化',
    '矿洗衣',
    '连采连充',
    '其他',
    '洗煤生产',
    '办公生活',
    '食堂',
    '采暖',
    '矿区内绿化',
    null,
    null,
    null,
    null,
    null,
    null,
  ],
]

// 水平衡汇总表
// eslint-disable-next-line
const reportId = REPORT_ID.WATER_BALANCE_SUMMARY
// eslint-disable-next-line
const formId = REPORT_FORM_ID.WATER_BALANCE_SUMMARY
// 当前企业名称
// const tenantName = ref('')
// 远程数据
const loadDataResponse = shallowRef<LoadDataResponse>()

const wrapper = ref<HTMLElement>()
const hot = ref<HandsonTable>()

const newMergeCells = shallowRef<any>(
  [
    { row: 0, col: 0, rowspan: 2, colspan: 1 },
    { row: 0, col: 1, rowspan: 2, colspan: 1 },
    { row: 0, col: 2, rowspan: 2, colspan: 1 },
    { row: 0, col: 3, rowspan: 1, colspan: 10 },
    { row: 0, col: 13, rowspan: 1, colspan: 5 },
    { row: 0, col: 18, rowspan: 2, colspan: 1 },
    { row: 0, col: 19, rowspan: 2, colspan: 1 },
    { row: 0, col: 20, rowspan: 2, colspan: 1 },
    { row: 0, col: 21, rowspan: 2, colspan: 1 },
    { row: 0, col: 22, rowspan: 2, colspan: 1 },
    { row: 0, col: 23, rowspan: 2, colspan: 1 },
  ],
)

// 加载数据
async function loadData() {
  if (!props.time) {
    return
  }
  const { data: res } = await loadReportDataOfSummaryCompanyWeight(props.time)
  const src = loadDataResponse.value = res
  const enterpriseList = src?.enterpriseList
  const getExp = (start: number) => {
    // 第一个单位初始行号是3
    const initial = 3
    // 列名
    const colStrs = 'CDEFGHIJKLMNOPQRSTUVW'.split('')
    const n = enterpriseList?.length ?? 0
    const ret = []
    for (let j = 0; j < colStrs.length; j++) {
      let exp = ''
      const colStr = colStrs[j]
      for (let i = 0; i < n; i++) {
        exp += `${colStr}${initial + i * 10 + start}+`
      }
      ret.push(`=ROUND(${exp.slice(0, -1)}, ${ROUND_NUMBER})`)
    }
    return ret
  }
  if (enterpriseList) {
    const dataList = []
    // 行号
    let row = 2
    // 循环插入企业水平衡数据
    for (let i = 0; i < enterpriseList.length; i++) {
      const v = enterpriseList[i]
      const v1 = v.dataList ?? []
      const v2 = v.dataTotalList ?? []
      if (v1.length === v2.length) {
        for (let j = 0; j < v1.length; j++) {
          // 取水对象
          const x1 = v1[j]
          // 取水累计对象
          const x2 = v2[j]
          row++
          const array1 = [
            // 单位名称
            j === 0 ? v.enterpriseName : null,
            x1.name,
            x1.qslTotal,
            x1.mkJxsc,
            x1.mkXy,
            x1.mkBgsh,
            x1.mkSt,
            x1.mkCn,
            x1.mkHbjc,
            x1.mkKqnlh,
            x1.mkKxy,
            x1.mkLclc,
            x1.mkQt,
            x1.xmcXmsc,
            x1.xmcShbg,
            x1.xmcSt,
            x1.xmcCn,
            x1.xmcKqnlh,
            x1.stzllhTotal,
            x1.lydwTotal,
            x1.wwdwTotal,
            x1.tslTotal,
            x1.sgsfylTotal,
            // 平衡情况 等待公式填充
            `=IF(SUM(D${row}:W${row})=C${row}+0, "平衡", "不平衡")`,
          ]
          row++
          const array2 = [
            null,
            '累计',
            x2.qslTotal,
            x2.mkJxsc,
            x2.mkXy,
            x2.mkBgsh,
            x2.mkSt,
            x2.mkCn,
            x2.mkHbjc,
            x2.mkKqnlh,
            x2.mkKxy,
            x2.mkLclc,
            x2.mkQt,
            x2.xmcXmsc,
            x2.xmcShbg,
            x2.xmcSt,
            x2.xmcCn,
            x2.xmcKqnlh,
            x2.stzllhTotal,
            x2.lydwTotal,
            x2.wwdwTotal,
            x2.tslTotal,
            x2.sgsfylTotal,
            // 平衡情况 等待公式填充
            `=IF(SUM(D${row}:W${row})=C${row}+0, "平衡", "不平衡")`,
          ]
          // 插入取水对象
          dataList.push(array1)
          // 接着插入取水累计对象
          dataList.push(array2)
        }
      }
      else {
        console.error('dataList.length !== dataTotalList.length')
      }
    }
    // 汇总行
    const summary = [
      ['汇总', REPORT_WATER_TYPE_TEXT.A, ...getExp(0), null],
      [null, '累计', ...getExp(1), null],
      [null, REPORT_WATER_TYPE_TEXT.B, ...getExp(2), null],
      [null, '累计', ...getExp(3), null],
      [null, REPORT_WATER_TYPE_TEXT.C, ...getExp(4), null],
      [null, '累计', ...getExp(5), null],
      [null, REPORT_WATER_TYPE_TEXT.D, ...getExp(6), null],
      [null, '累计', ...getExp(7), null],
      [null, REPORT_WATER_TYPE_TEXT.E, ...getExp(8), null],
      [null, '累计', ...getExp(9), null],
    ]
    hot.value?.loadData([
      ...HEADERS,
      ...dataList,
      ...summary,
    ])
  }
}

// 更新单元格合并
function updateSettings() {
  if (hot.value) {
    const defaults = newMergeCells.value
    const mergeCells = [
      ...defaults,
    ]
    const src = loadDataResponse.value
    const length = src?.enterpriseList?.length
    // 单位名称合并，每个单位合并10行（5个取水名称和5个累计）
    // 从行号3开始
    if (length) {
      for (let i = 0; i < length; i++) {
        mergeCells.push({
          row: 2 + i * 10,
          col: 0,
          rowspan: 10,
          colspan: 1,
        })
      }
      // 汇总第A列合并
      // 汇总起始行索引=表格总行数-10
      const rows = 2 + length * 10 + 10
      mergeCells.push({
        row: rows - 10,
        col: 0,
        rowspan: 10,
        colspan: 1,
      })
    }

    hot.value.updateSettings({
      mergeCells,
    })
  }
}

function init() {
  if (!wrapper.value)
    return
  hot.value = new HandsonTable(wrapper.value, {
    fixedColumnsStart: 2,
    fixedRowsTop: HEADERS.length,
    readOnly: true,
    // disableVisualSelection: true,
    language: zhCN.languageCode,
    formulas: {
      engine: HyperFormula,
    },
    cells(row, column) {
      if (row < HEADERS.length || column < 2) {
        return { className: `htCenter htMiddle ${HEADER_CELL_CLASS}` }
      }
      return { className: `htCenter htMiddle` }
    },
    readOnlyCellClassName: READONLY_CELL_CLASS,
    stretchH: 'all',
    // autoColumnSize: true,
    colWidths: 100,
    manualColumnResize: true,
    colHeaders: true,
    rowHeaders: true,
    mergeCells: [],
    licenseKey: 'non-commercial-and-evaluation',
  })

  // debug
  if (import.meta.env.VITE_REPORT_DEBUG === '1') {
    hot.value.addHook('afterSelection', (row, col) => {
      if (row > -1 && col > -1) {
        console.info(`[${row},${col}] ${hot.value?.getSourceDataAtCell(row, col)}`)
        document.execCommand('copy')
      }
    })
  }
}

const { isDark } = useTheme(async () => {
  // 主题切换后，重新初始化实例
  if (hot.value) {
    hot.value.destroy()
    hot.value = undefined
    await bootstrap()
  }
})

async function bootstrap() {
  // 初始化实例
  init()
  // 加载数据和配置
  await loadData()
  // 更新单元格配置
  updateSettings()
}

onMounted(bootstrap)
</script>

<template>
  <div class="h-full w-full">
    <div
      ref="wrapper" class="h-full w-full overflow-auto" :class="{
        'ht-theme-main-dark': isDark,
        'ht-theme-main': !isDark,
      }"
    />
  </div>
</template>
